package com.gxd.ssoserver.aspect;

import com.gxd.commons.utils.IPAddressUtils;
import com.gxd.commons.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author:gxd
 * @Description:@Pointcut定义的切入点为com.gxd.ssoserver.web
 * 包下的所有函数（对web层所有请求处理做切入点）
 * 然后通过@Before实现，对请求内容的日志记录
 * 最后通过@AfterReturning记录请求返回的对象。
 * @Date: 9:19 2018/2/13
 * @Modified By:
 */
@Aspect
@Component
public class WebLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 两个..代表所有子目录，最后括号里的两个..代表所有参数
     */
    @Pointcut("execution(public * com.gxd.ssoserver.web..*.*(..))")
    public void webLog(){

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + IPAddressUtils.getIpAddress(request));
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    /**
     * returning的值和doAfterReturning的参数名一致
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
        logger.info("SPEND TIME : " + StringUtils.formatDuring(System.currentTimeMillis() - startTime.get()));
    }
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object ob = pjp.proceed();// ob 为方法的返回值
        logger.info("SPEND TIME : " + StringUtils.formatDuring(System.currentTimeMillis() - startTime.get()));
        return ob;
    }
}
